package com.chase.framerwork.interceptor;

import org.apache.commons.lang3.time.StopWatch;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 拦截器 - 调试信息,记录日志,用户执行了哪个类，花费了多长时间，转发到哪个页面都有详细记录。
 * 
 * @Author Chase
 * @Date 2013-10-30
 */
public class DebugLoggerInterceptor extends AbstractInterceptor
{
	private static final Logger logger = LogManager.getLogger(DebugLoggerInterceptor.class);

	private static final long serialVersionUID = -974129429866051172L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception
	{
		StopWatch s = new StopWatch(); // 计时器
		s.start(); // 开始计时

		String result = null;
		String location = null;

		try
		{
			result = invocation.invoke();
		}
		catch (Exception e)
		{
			logger.error(e);
			e.printStackTrace();
			throw e;
		}

		ActionProxy actionProxy = invocation.getProxy();
		ActionConfig config = actionProxy.getConfig();

		ResultConfig resultConfig = config.getResults().get(result);
		if (resultConfig != null)
		{
			location = resultConfig.getParams().get("location");
		}
		else
		{
			location = Action.NONE;
		}

		s.stop(); // 结束计时

		logger.info(buildDebugMessage(config.getClassName(), actionProxy.getMethod(), location, s.getTime()));

		return result;
	}
	
	/**
	 * 构造调试信息
	 * 
	 * @param className 类名
	 * @param methodName 方法名
	 * @param location 转发地址
	 * @param spendTime 耗时(毫秒)
	 * @return
	 */
	private String buildDebugMessage(String className,String methodName,String location,Long spendTime){
		StringBuffer message = new StringBuffer();
		message.append("\r\n");
		message.append("<execute-class ");
		message.append(className);
		message.append(">\r\n<invok-method ");
		message.append(methodName);
		message.append("()>\r\n<forward-location ");
		message.append(location);
		message.append(">\r\n<spend-time ");
		message.append(spendTime);
		message.append(" ms.>");
		
		return message.toString();
	}
}
